/**
 * Created by xusheng on 2018/7/10 0010.
 */
import axios from "axios";
import { ElMessage, ElMessageBox } from "element-plus";
axios.defaults.timeout = 320000;

const getAccessToken = () => {
  return localStorage.ls_token
}

//http request 拦截器
axios.interceptors.request.use(
  (config) => {
    config.headers = {
      "Content-Type": "application/json",
    };
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//响应拦截器即异常处理
axios.interceptors.response.use(
  (response) => {
    return response;
  },
  (err) => {
    let errorText = "";
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          errorText = "错误请求";
          break;
        case 401:
          errorText = "未授权，请重新登录";
          ElMessage.error('登录已过期，请重新登陆')
          setTimeout(() => {
            localStorage.clear()
            window.location.replace("/")
          }, 500);
          break;
        case 403:
          errorText = "拒绝访问";
          break;
        case 404:
          errorText = "请求错误,未找到该资源";
          break;
        case 405:
          errorText = "请求方法未允许";
          break;
        case 408:
          errorText = "请求超时";
          break;
        case 500:
          errorText = "服务器端出错";
          break;
        case 501:
          errorText = "网络未实现";
          break;
        case 502:
          errorText = "网络错误";
          break;
        case 503:
          errorText = "服务不可用";
          break;
        case 504:
          errorText = "网络超时";
          break;
        case 505:
          errorText = "http版本不支持该请求";
          break;
        default:
          errorText = `连接错误${err.response.status}`;
      }
    } else {
      errorText = "连接到服务器失败";
    }
    return Promise.reject(errorText);
  }
);

export async function HTTP(url = "", params = {}, methods = "post") {
  return new Promise((resolve, reject) => {
    axios[methods](url, params)
      .then(({ data }) => {
        if (data.code !== 0 && data.status !== '200') {
          reject(data.msg);
        } else {
          resolve(data);
        }
      })
      .catch((err) => {
        reject(err);
      });
  });
}